////
////  RequestBaoXiaoViewController.swift
////  HuaYun
////
////  Created by Mac on 2019/3/19.
////  Copyright © 2019 xyxorigation. All rights reserved.
////
//
import UIKit
import RxSwift
import RxCocoa

protocol GiveNumber {
    func number(number: Double) -> Void
}

class ImportTableViewCell: UITableViewCell,UITextFieldDelegate {
    
    var delegate: GiveNumber?
    var isnumber: Bool = false
    private var _isimportant = false
    var isimportant: Bool{
        get{
            return _isimportant
        }
        set{
            _isimportant = newValue
            if _isimportant {
                //红星
//                self.starLabel.snp.updateConstraints { (make) in
//                    make.width.equalTo(12)
//                }
                self.starLabel.isHidden = false
            } else {
                self.starLabel.isHidden = true
                //无红星
//                self.starLabel.snp.updateConstraints { (make) in
//                    make.width.equalTo(0)
//                }
            }
        }
    }
    
    private var _caninput: Bool = false
    
    var caninput: Bool{
        get{
            return _caninput
        }
        set{
            _caninput = newValue
            if _caninput {
                self.inputField.isEnabled = true
            } else {
                self.inputField.isEnabled = false
            }
        }
    }
    
    let starLabel = UILabel()
    let nameLabel = UILabel()
    let inputField = UITextField()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.configView()
    }
    
    func configView(){
        self.contentView.addSubview(starLabel)
        self.contentView.addSubview(nameLabel)
        self.contentView.addSubview(inputField)
        starLabel.textColor = UIColor.red
        starLabel.font = UIFont.systemFont(ofSize: 12)
        starLabel.text = "*"
        starLabel.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(15)
            make.width.equalTo(12)
            make.height.equalTo(12)
        }
        nameLabel.textColor = UIColor.hex("333333")
        nameLabel.font = UIFont.boldSystemFont(ofSize: 18)
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(starLabel.snp.right)
            make.centerY.equalTo(starLabel.snp.centerY)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(20)
        }
        inputField.placeholder = "请选择"
        inputField.snp.makeConstraints { (make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(8)
            make.left.equalTo(nameLabel.snp.left)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(25)
        }
        inputField.delegate = self
        inputField.addTarget(self, action: #selector(change), for: .editingChanged)
    }
    
    @objc func change(){
        let s = self.inputField.text ?? ""
        let number = Double.init(s) ?? 0.0
        self.delegate?.number(number: number)
    }
    
    private var havingDot = false
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "" {
            return true
        }
        if string.count > 1 {
            if self.isnumber {
                return false
            } else {
                return true
            }
        }
        if self.isnumber {
            if string != "." {
                let val = Double.init(string)
                if val == nil {
                    return false
                }
            }
        }
        if string == "." {
            if (textField.text?.contains(".") ?? false) == true {
                return false
            } else {
                return true
            }
        }
        if (textField.text?.contains(".") ?? false) == true {
            let distance = textField.text!.distance(from: textField.text!.range(of: ".")!.upperBound, to: textField.text!.endIndex)
            if distance < 2 {
                return true
            } else {
                return false
            }
        } else {
            return true
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.configView()
    }
    
}

class RequestBaoXiaoViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate,FetchResult,GiveNumber {
    
    var currentticket = 0
    
    func giveModel(json: JSON) {
        
        let projinfo = self.projectSources[self.selectedProj]
        projinfo.0.accept(json)
    }
    
    func giveModels(jsons: [JSON]) {
        
    }
    
    func number(number: Double) {
//        let total = self.tickets.reduce(0.0) { (result, element) -> Double in
//            let totalstr = element.2
//            let totalval = Double.init(totalstr ?? "") ?? 0.0
//            return result + totalval
//        }
//        self.bxhstotal.accept(String.init(format: "%.2f", total))
//        self.bxhstotalbig.accept(String.init(format: "%.2f", total).rmbOldStyle)
//        let partial = self.tickets.reduce(0.0) { (result, element) -> Double in
//            let partialstr = element.3
//            let partialaccount = Double.init(partialstr ?? "") ?? 0.0
//            return result + partialaccount
//        }
//        self.bxnothstotal.accept(String.init(format: "%.2f", partial))
//        self.shuie.accept(String.init(format: "%.2f", total - partial))
    }

    //报销付款金额
    var bxfkje: BehaviorRelay<String?> = BehaviorRelay<String?>.init(value: "0")
    
//    var isSure = PublishSubject<Bool>()//是否已签合同
//    var contractType: PublishSubject<(Bool,Bool,Bool)> = PublishSubject
    var contractType: BehaviorRelay<(Bool,Bool,Bool)> = BehaviorRelay<(Bool,Bool,Bool)>.init(value: (true,false,false))
    
    var projectinfo: PublishSubject<JSON?> = PublishSubject<JSON?>.init()//项目名称
    
    var comprehensivePlan = PublishSubject<String?>.init()//综合计划名称
    
    var phone = BehaviorRelay<String?>.init(value: "")//联系电话双向绑定
    
    var bigtype = PublishSubject<JSON?>.init()//报销大类
    
    var subtype = PublishSubject<JSON?>.init()//报销小类
    
    var tickets: [(BehaviorRelay<JSON?>,BehaviorRelay<JSON?>,BehaviorRelay<String?>,BehaviorRelay<String?>)] = [(BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<String?>.init(value: nil),BehaviorRelay<String?>.init(value: nil))]//发票明细
    
    var bxhstotal =  BehaviorRelay<String?>.init(value: nil)//报销含税总金额
    
    var bxhstotalbig = BehaviorRelay<String?>.init(value: nil)// 报销含税总金额大写
    
    var bxnothstotal = BehaviorRelay<String?>.init(value: nil)//报销不含税
    
    var shuie = BehaviorRelay<String?>.init(value: nil)
    
    var reason = BehaviorRelay<String?>.init(value: nil)
    
    var tableView = UITableView.init()
    
    var bag = DisposeBag()
    
    var files: [(UIImage,String)] = []
    
    var rats: [JSON] = []//税率
    var uploadfilespath: [[String:String]] = []
    
    @objc func submitAction(){
        if (self.remainingft.value ?? -1) < 0 {
            self.alert("分摊金额超出发票总额!");
            return
        }
        if (self.remainingft.value ?? -1) > 0 {
            self.alert("分摊金额有剩余!");
            return
        }
        if self.contractType.value.0 == true {
            self.alert("非手工合同请走采购付款流程")
            return
        }
        if self.contractType.value.1 == true {
            self.params["yesOrNotContract"] = 0
        } else if self.contractType.value.2 == true {
            self.params["yesOrNotContract"] = 2
        }
        let bigtyperesult = self.valid(key: "reimbursementBigTypeId")
        if bigtyperesult == false {
            self.alert("请选择报销大类")
            return
        }
        let subtyperesult = self.valid(key: "reimbursementSmallTypeId")
        if subtyperesult == false {
            self.alert("请选择报销子类")
            return
        }
        
        if (self.bxfkje.value?.count ?? 0) == 0 {
            self.alert("请输入报销付款金额")
            return
        }
        
        for i in 0 ..< self.tickets.count {
            let codekey = "reimbursementDetails[" + String(i) + "].invoiceType"
            let ratekey = "reimbursementDetails[" + String(i) + "].taxrate"
            let taxMoney = "reimbursementDetails[" + String(i) + "].taxMoney"
            let notTaxMoney = "reimbursementDetails[" + String(i) + "].notTaxMoney"
            self.params[codekey] = self.tickets[i].0.value?["invoicesCode"].int
            self.params[ratekey] = self.tickets[i].1.value?["id"].string
            let money = (Double.init(self.tickets[i].2.value ?? "") ?? 0.0) * 100.0
            self.params[taxMoney] = Int(money)
            let notall = (Double.init(self.tickets[i].3.value ?? "") ?? 0.0) * 100.0
            self.params[notTaxMoney] = Int(notall)
            
            if self.valid(key: codekey) == false {
                self.alert("请选择发票类型")
                return
            }
            if self.valid(key: ratekey) == false {
                self.alert("请选择税率类型")
                return
            }
            if self.valid(key: taxMoney) == false {
                self.alert("请输入含税金额")
                return
            }
            if self.valid(key: notTaxMoney) == false {
                self.alert("请输入不含税金额")
                return
            }
        }
        
        for i in 0 ..< self.projectSources.count {
            let projId = "reimbursementProjects[" + String(i) + "].projId"
            if self.projectSources[i].0.value == nil {
                self.alert("请选择项目或删除空项目")
                return
            }
            self.params[projId] = self.projectSources[i].0.value?["id"].string
            let manager = "reimbursementProjects[" + String(i) + "].projManager"
            let comprehensivenum = "reimbursementProjects[" + String(i) + "].comprehensivePlanNumber"
            let taxMoney = "reimbursementProjects[" + String(i) + "].comprehensivePlanName"
            let proj = "reimbursementProjects[" + String(i) + "].projNumber"
            let orgCode = "reimbursementProjects[" + String(i) + "].orgCode"
            let deptName = "reimbursementProjects[" + String(i) + "].deptName"
            let projName = "reimbursementProjects[" + String(i) + "].projName"
            let projCost = "reimbursementProjects[" + String(i) + "].projCost"
//            let bxman = "reimbursementProjects[" + String(i) + "].concernedHuman"
            self.params[orgCode] = self.projectSources[i].0.value?["projectApplyOrgCode"].string
            self.params[deptName] = self.projectSources[i].0.value?["applyDept"].string
            self.params[projName] = self.projectSources[i].0.value?["gsProjName"].string
            self.params[proj] = self.projectSources[i].0.value?["projectNumber"].string
            let coststr = self.projectSources[i].1.value ?? "0"
            let cost = Double.init(coststr) ?? 0
            self.params[projCost] = cost * 100
            self.params[manager] = self.projectSources[i].0.value?["projManager"].string
            self.params[comprehensivenum] = self.projectSources[i].0.value?["serialnumber"].string
            self.params[taxMoney] = self.projectSources[i].0.value?["compositeName"].string
//            self.params[bxman] = self.projectSources[i].2.value ?? ""
        }

        if let ph = self.params["phone"] as? String{
            if ph.isEmpty == false {
                if ph.isPhone == false {
                    self.alert("请输入正确的手机号")
                    return
                }
            }
        }
        
        self.beginLoading()
        
        self.params["applyTime"] = Date().dateLineStr
        
        if self.files.count > 0 {
            //先上传再提交
            let filedatas = files.map { (element) -> Data in
                return element.0.pngData() ?? Data()
            }
            var uploadsuccess = 0
            for _ in 0 ..< self.files.count {
                NetManager.upload(UPLOADPATH, nil, filedatas, name: "file", suc: { (json) in
                    self.endLoading()
                    if json.contents?["success"]?.bool == true {
                        let data = json.contents?["data"]?.contents
                        var dic: Dictionary<String,String> = [:]
                        dic["path"] = data?["path"]?.rawString() ?? ""
                        dic["name"] = data?["name"]?.rawString() ?? ""
                        dic["fileSize"] = String((data?["fileSize"]?.int ?? 0))
                        dic["absolutePath"] = data?["absolutePath"]?.rawString() ?? ""
                        self.uploadfilespath.append(dic)
                        uploadsuccess += 1
                        if uploadsuccess == self.files.count {
                            var uploaddic: [String:String] = [:]
                            for i in 0 ..< self.uploadfilespath.count {
                                let item = self.uploadfilespath[i]
                                for key in item.keys {
                                    let destkey = "attachFiles[" + String(i) + "]" + "." + key
                                    uploaddic[destkey] = item[key]
                                }
                            }
                            NetManager.post(AddBXApproval, self.params + uploaddic, suc: { (json) in
                                self.endLoading()
                                if json["success"].bool == true {
                                    NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: nil)
                                    self.pop()
                                } else {
                                    self.alert(json["errMessage"].string)
                                }
                            }) { (error) in
                                self.endLoading()
                                self.alert(error.localizedDescription)
                            }
                        }
                    } else {
                        self.alert(json.contents?["errorMsg"]?.rawString())
                    }
                }) { (error) in
                    self.endLoading()
                    self.alert(error.localizedDescription)
                }
            }
        } else {
            NetManager.post(AddBXApproval, self.params, suc: { (json) in
                self.endLoading()
                if json["success"].bool == true {
                    NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: nil)
                    self.pop()
                } else {
                    self.alert(json["errorMsg"].string)
                }
            }) { (error) in
                self.endLoading()
                self.alert(error.localizedDescription)
            }
        }
    }
    
    var shuiebx: String?{
        get{
            let total = Double.init(self.bxhstotal.value ?? "") ?? 0.0
            let nottotal = Double.init(self.bxnothstotal.value ?? "") ?? 0.0
            return String.init(format: "%.2f", total - nottotal)
        }
    }
    
    var filepaths: [String] = []
    
    func valid(key: String)->Bool{
        if let value = self.params[key] {
            if let str = value as? String{
                if str.count > 0 {
                    return true
                } else {
                    return false
                }
            }
            if let _ = value as? Double {
                return true
            } else  {
                if let _ = value as? Int {
                    return true
                }
                return false
            }
        }
        return false
    }
    
    var params: [String: Any] = ["":""]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.keyboardDismissMode = .onDrag
        self.bxhstotal.subscribe { [weak self](event) in
            let total = event.element ?? ""
            let remaining = self?.bxnothstotal.value ?? ""
            let totaldouble = Double.init(total ?? "") ?? 0.0
            let remainingdouble = Double.init(remaining) ?? 0.0
            self?.shuie.accept(String.init(format: "%.2f", totaldouble - remainingdouble))
            }.disposed(by: bag)
        
        self.bxnothstotal.subscribe { [weak self](event) in
            let remaining = event.element ?? ""
            let total = self?.bxhstotal.value ?? ""
            let totaldouble = Double.init(total) ?? 0.0
            let remainingdouble = Double.init(remaining ?? "") ?? 0.0
            self?.shuie.accept(String.init(format: "%.2f", totaldouble - remainingdouble))
            }.disposed(by: bag)
        self.bxhstotal.map({return $0?.rmbOldStyle})
            .subscribe(onNext: { [weak self](str) in
                self?.bxhstotalbig.accept(str)
            }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.navigationItem.hidesBackButton = true
        if self.navigationController != nil {
            if let index = self.navigationController?.children.firstIndex(of: self) {
                if index > 0 {
                    let back = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_whiteback")!.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(pop))
                    self.navigationItem.leftBarButtonItem = back
                } else {
                    self.navigationItem.leftBarButtonItem = nil
                }
            }
        }
        self.bxfkje.subscribe(onNext: { [weak self](str) in
            let money = Double.init((str ?? "")) ?? 0.0
            self?.params["reimbursementPayMoney"] = Int(money * 100)
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.projectinfo.subscribe(onNext: { [weak self](json) in
            self?.params["projid"] = json?["id"].string ?? ""
            self?.params["projNumber"] = json?["projectNumber"].string ?? ""
            self?.params["projName"] = json?["gsProjName"].string ?? ""
            self?.params["applyDeptOrgcode"] = json?["projectApplyOrgCode"].string ?? ""
            self?.params["comprehensivePlanName"] = json?["comprehensivePlanName"].string ?? ""
            self?.params["comprehensivePlanNumber"] = json?["comprehensivePlanNumber"].string ?? ""
            
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.bigtype.subscribe(onNext: { [weak self](element) in
            self?.params["reimbursementBigTypeName"] = element?["name"].string ?? ""
            self?.params["reimbursementBigTypeId"] = element?["id"].string ?? ""
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        
        self.subtype.subscribe(onNext: { [weak self](element) in
            self?.params["reimbursementSmallTypeName"] = element?["name"].string ?? ""
            self?.params["reimbursementSmallTypeId"] = element?["id"].string ?? ""
            }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.phone.subscribe(onNext: { (str) in
            self.params["phone"] = str ?? ""
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        //时间容后处理
        self.bxhstotal.subscribe(onNext: { [weak self](str) in
            if let money = Double.init(str ?? "") {
                self?.params["reimbursementMoney"] = Int(money * 100)
            }
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.bxnothstotal.subscribe(onNext: { [weak self](str) in
            if let money = Double.init(str ?? "") {
                self?.params["reimbursementMoneyNotTax"] = Int(money * 100)
            }
            }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.reason.subscribe(onNext: { [weak self](str) in
            self?.params["reimbursementReason"] = str ?? 0
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        self.view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-55)
        }
        
        let subButton = UIButton.init(type: .system)
        subButton.setTitle("提交申请", for: .normal)
        subButton.setBackgroundImage(UIColor.mainColor.image(size: CGSize(width: self.view.width, height: 55)), for: .normal)
        subButton.setBackgroundImage(UIColor.hex("eeeeee").image(size: CGSize(width: self.view.width, height: 55)), for: .disabled)
        subButton.setTitleColor(UIColor.white, for: .normal)
        subButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        self.view.addSubview(subButton)
        subButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(55)
        }
        
        subButton.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        //初始状态下注册足够用的cell
        sureForUse()
        
        let header = UIView()
        self.tableView.tableHeaderView = header
        header.frame = CGRect.init(origin: .zero, size: CGSize(width: self.view.width, height: 55))
        let stackView = UIStackView.init(frame: header.bounds)
        header.addSubview(stackView)
        stackView.alignment = .center
        stackView.spacing = 10
        stackView.axis = .horizontal
        stackView.distribution = .fillProportionally
        let button = UIButton.init(type: .custom)
        button.setImage(UIImage.init(named: "icon_choose_selected"), for: .selected)
        button.setImage(UIImage.init(named: "icon_choose_normal"), for: .normal)
        button.setTitleColor(UIColor.hex("333333"), for: .normal)
        button.setTitle("非手工创建合同", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        let notbutton = UIButton.init(type: .custom)
        notbutton.setImage(UIImage.init(named: "icon_choose_selected"), for: .selected)
        notbutton.setImage(UIImage.init(named: "icon_choose_normal"), for: .normal)
        notbutton.setTitleColor(UIColor.hex("333333"), for: .normal)
        notbutton.setTitle("手工创建合同", for: .normal)
        notbutton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        stackView.addArrangedSubview(button)
        stackView.addArrangedSubview(notbutton)
        
        let otherbutton = UIButton.init(type: .custom)
        otherbutton.setImage(UIImage.init(named: "icon_choose_selected"), for: .selected)
        otherbutton.setImage(UIImage.init(named: "icon_choose_normal"), for: .normal)
        otherbutton.setTitleColor(UIColor.hex("333333"), for: .normal)
        otherbutton.setTitle("无合同", for: .normal)
        otherbutton.isSelected = false
        otherbutton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        otherbutton.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self]() in
            self?.contractType.accept((false,false,true))
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: self.bag)
        stackView.addArrangedSubview(otherbutton)
        
        self.contractType.map({$0.0}).bind(to: button.rx.isSelected).disposed(by: self.bag)
        self.contractType.map({$0.1}).bind(to: notbutton.rx.isSelected).disposed(by: self.bag)
        self.contractType.map({$0.2}).bind(to: otherbutton.rx.isSelected).disposed(by: self.bag)
        
        button.rx.controlEvent(.touchUpInside).asObservable().subscribe(onNext: { [weak self]() in
            self?.contractType.accept((true,false,false))
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        
        button.isSelected = true
        notbutton.rx.controlEvent(.touchUpInside).asObservable().subscribe(onNext: { [weak self]() in
            self?.contractType.accept((false,true,false))
            }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: bag)
        let line = UIView()
        line.backgroundColor = UIColor.hex("eeeeee")
        header.addSubview(line)
        line.frame = CGRect.init(x: 15, y: 54, width: self.view.width - 15, height: 1)
        
        self.getTypeList(id: nil)
        
        self.getTicketsType()
        
        self.getRats()
    }
    
    var tickettypes: [JSON] = []
    
    func getRats(){
        self.beginLoading()
        NetManager.get(RatioType, nil, suc: { (json) in
            self.endLoading()
            self.rats = json["data"].array ?? []
            if self.rats.count > 0 {
                let target = self.rats.filter({ (json) -> Bool in
                    return (json["taxrateType"].string ?? "") == "0%"
                })
                if target.count > 0 {
                    self.tickets[0].1.accept(target[0])
                }
            }
        }) { (error) in
            self.endLoading()
            self.alert(error.localizedDescription)
        }
    }
    
    func getTicketsType(){
        self.beginLoading()
        NetManager.get(TicketType, nil, suc: { (json) in
            self.endLoading()
            self.tickettypes = json["data"].array ?? []
            if self.tickettypes.count > 0 {
                self.tickets[0].0.accept(self.tickettypes[0])
            }
            self.tickets[0].2.accept("0")
            self.tickets[0].3.accept("0")
        }) { (error) in
            self.endLoading()
            self.alert(error.localizedDescription)
        }
    }
    
    var currentdatestr: String = ""
    
    var importantcells: [ImportTableViewCell] = []
    
    var projectSources: [(BehaviorRelay<JSON?>,BehaviorRelay<String?>)] = [(BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<String?>.init(value: "0"))]
    
    //分摊总额
    var fttotal: BehaviorRelay<String?> = BehaviorRelay<String?>.init(value: nil)
    var remainingft: BehaviorRelay<Double?> = BehaviorRelay<Double?>.init(value: nil)
    func sureForUse(){
        self.importantcells.removeAll()
        Observable.combineLatest(self.projectSources.map({$0.1}))
            .map { [weak self](strarr) -> Double? in
                let total = strarr.reduce(0, { (result, element) -> Double in
                    return result + (Double.init(element ?? "0") ?? 0.0)
                })
                let fttal = self?.fttotal.value ?? "0"
                let totalval = Double.init(fttal) ?? 0.0
                return totalval - total
        }.bind(to: self.remainingft).disposed(by: bag)
        self.fttotal.map { [weak self](element) -> Double in
            let arrays = self!.projectSources.map({Double.init($0.1.value ?? "0")})
            let total = arrays.reduce(0.0, { (result, value) -> Double in
                return result + (value ?? 0.0)
            })
            let ftt = Double.init(self?.fttotal.value ?? "0") ?? 0.0
            return ftt - total
            }.bind(to: self.remainingft).disposed(by: bag)
        for i in 0 ..< 4 {
            let id = "head" + String(i)
            self.tableView.register(ImportTableViewCell.classForCoder(), forCellReuseIdentifier: id)
            if let cell = self.tableView.dequeueReusableCell(withIdentifier: id) as? ImportTableViewCell {
                self.importantcells.append(cell)
                if i == 0 {
                    cell.nameLabel.text = "报销类型(大):"
                    cell.isimportant = true
                    cell.caninput = false
                    cell.accessoryType = .disclosureIndicator
                    cell.selectionStyle = .none
                    self.bigtype.subscribe(onNext: { (str) in
                        cell.inputField.text = str?["name"].string
                    }).disposed(by: bag)
                } else if i == 1 {
                    cell.nameLabel.text = "报销类型(小):"
                    cell.isimportant = true
                    cell.caninput = false
                    cell.accessoryType = .disclosureIndicator
                    cell.selectionStyle = .none
                    self.subtype.subscribe(onNext: { (str) in
                        cell.inputField.text = str?["name"].string
                    }).disposed(by: bag)
                } else if i == 2 {
                    cell.nameLabel.text = "报销付款金额(元):"
                    cell.isimportant = true
                    cell.caninput = true
                    cell.isnumber = true
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    self.bxfkje.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.rx.text.bind(to: self.bxfkje).disposed(by: bag)
                    cell.inputField.placeholder = "请输入"
                    cell.inputField.keyboardType = .numbersAndPunctuation
                } else {
                    cell.nameLabel.text = "联系电话:"
                    cell.isimportant = false
                    cell.caninput = true
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    phone.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.rx.text.bind(to: self.phone).disposed(by: bag)
                    cell.inputField.placeholder = "请输入"
                    cell.inputField.keyboardType = .phonePad
                }
            }
        }
        
        self.currentdatestr = Date().dateStr.md5
        for i in 1 ... self.tickets.count {
            for j in 0 ..< 4 {
                let id = "ImportTableViewCell" + self.currentdatestr + String(i) + String(j)
                tableView.register(ImportTableViewCell.classForCoder(), forCellReuseIdentifier: id)
                if let cell = tableView.dequeueReusableCell(withIdentifier: id) as? ImportTableViewCell {
                    self.importantcells.append(cell)
                    if j == 0 {
                        cell.nameLabel.text = "发票类型:"
                        cell.isimportant = true
                        cell.caninput = false
                        cell.accessoryType = .disclosureIndicator
                        cell.selectionStyle = .none
                        self.tickets[i - 1].0.map({return $0?["invoicesType"].string})
                            .bind(to: cell.inputField.rx.text).disposed(by: bag)
                        self.tickets[i - 1].0.map({return $0?["invoicesCode"].int})
                            .map { [weak self](value) -> String in
                                let fttotals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                    var val: Double = 0.0
                                    let elementtype = element.0.value?["invoicesCode"].int ?? -1
                                    if elementtype == 3 {
                                        val = Double.init(element.3.value ?? "") ?? 0.0
                                    } else {
                                        val = Double.init(element.2.value ?? "") ?? 0.0
                                    }
                                    return val + res
                                })
                                return String.init(format: "%.2f", fttotals ?? 0.0)
                        }.bind(to: self.fttotal).disposed(by: bag)
                        self.tickets[i - 1].0.accept(self.tickets[i - 1].0.value)
                    } else if j == 1 {
                        cell.nameLabel.text = "税率:"
                        cell.isimportant = true
                        cell.caninput = false
                        cell.accessoryType = .disclosureIndicator
                        cell.selectionStyle = .none
                        self.tickets[i - 1].1.map({return $0?["taxrateType"].string})
                            .bind(to: cell.inputField.rx.text).disposed(by: bag)
                        self.tickets[i - 1].1.map { [weak self](element) -> String in
                            let ratio = self?.tickets[self?.index(for: i - 1) ?? 0].1.value?["taxrateType"].string ?? ""
                            let rat = ratio.replacingOccurrences(of: "%", with: "")
                            let ratiodouble = (Double.init(rat) ?? 0.0) / 100.0
                            let val = Double.init(self?.tickets[self?.index(for: i - 1) ?? 0].2.value ?? "") ?? 0.00
                            return String.init(format: "%.2f", val / (1 + ratiodouble))
                            }.bind(to: self.tickets[i - 1].3).disposed(by: bag)
                        self.tickets[i - 1].1.accept(self.tickets[i - 1].1.value)
                        //更新一次
                    } else if j == 2 {
                        cell.nameLabel.text = "含税金额(元):"
                        cell.isimportant = true
                        cell.caninput = true
                        cell.accessoryType = .none
                        cell.selectionStyle = .none
                        cell.inputField.placeholder = "请输入"
                        cell.isnumber = true
                        cell.inputField.keyboardType = .numbersAndPunctuation
                        cell.delegate = self
                        self.tickets[i - 1].2.bind(to: cell.inputField.rx.text).disposed(by: bag)
                        cell.inputField.rx.text.bind(to: self.tickets[i - 1].2).disposed(by: bag)
                        self.tickets[i - 1].2.map { [weak self](element) -> String? in
                            let val = Double.init(element ?? "") ?? 0.00
                            let rat = (self?.tickets[self?.index(for: i - 1) ?? 0].1.value?["taxrateType"].string ?? "").replacingOccurrences(of: "%", with: "")
                            let ratval = (Double.init(rat) ?? 0.0) / 100.0
                            
                            let bxhstotals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                let val = Double.init(element.2.value ?? "") ?? 0.0
                                return val + res
                            })
                            self?.bxhstotal.accept(String.init(format: "%.2f", bxhstotals ?? 0.0))
                            return String.init(format: "%.2f", val / (1 + ratval))
                            }
                            .bind(to: self.tickets[i - 1].3)
                            .disposed(by: bag)
                        self.tickets[i - 1].2.accept(self.tickets[i - 1].2.value)
                        //fttotal
                    } else if j == 3 {
                        cell.nameLabel.text = "不含税金额(元):"
                        cell.isimportant = false
                        cell.caninput = true
                        cell.accessoryType = .none
                        cell.selectionStyle = .none
                        cell.isnumber = true
                        cell.inputField.placeholder = "请输入"
                        cell.inputField.keyboardType = .numbersAndPunctuation
                        self.tickets[i - 1].3.bind(to: cell.inputField.rx.text).disposed(by: bag)
                        cell.inputField.rx.text.bind(to: self.tickets[i - 1].3).disposed(by: bag)
                        self.tickets[i - 1].3.map { [weak self](element) -> String? in
                            let nottotals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                let val = Double.init(element.3.value ?? "") ?? 0.0
                                return val + res
                            })
                            return String.init(format: "%.2f", nottotals ?? 0.0)
                            }
                            .bind(to: self.bxnothstotal)
                            .disposed(by: bag)
                        self.tickets[i - 1].3.map { [weak self](element) -> String? in
                            let totals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                let val = Double.init(element.2.value ?? "") ?? 0.0
                                return val + res
                            }) ?? 0.0
                            let nottotals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                let val = Double.init(element.3.value ?? "") ?? 0.0
                                return val + res
                            }) ?? 0.0
                            return String.init(format: "%.2f", totals - nottotals)
                            }
                            .bind(to: self.shuie)
                            .disposed(by: bag)
                        self.tickets[i - 1].3.map { [weak self](val) -> String? in
                            let fttotals = self?.tickets.reduce(0.0, { (res, element) -> Double in
                                let value = element.0.value?["invoicesCode"].int ?? 0
                                var val: Double = 0.0
                                if value == 3 {
                                    val = Double.init(element.3.value ?? "") ?? 0.0
                                } else {
                                    val = Double.init(element.2.value ?? "") ?? 0.0
                                }
                                return val + res
                            })
                            return String.init(format: "%.2f", fttotals ?? 0.0)
                            }
                            .bind(to: self.fttotal)
                            .disposed(by: bag)
                        if i == self.projectSources.count - 1 {
                            
                        }
                        self.tickets[i - 1].3.accept(self.tickets[i - 1].3.value)
                    }
                }
            }
        }
        
        //项目
        for i in 0 ..< self.projectSources.count {
            let projinfo = self.projectSources[i]
            for j in 0 ..< 4 {
                let id = "projectinfo" + String(i) + String(j)
                self.tableView.register(ImportTableViewCell.classForCoder(), forCellReuseIdentifier: id)
                if let cell = self.tableView.dequeueReusableCell(withIdentifier: id) as? ImportTableViewCell {
                    self.importantcells.append(cell)
                    if j == 0 {
                        cell.nameLabel.text = "项目名称:"
                        cell.isimportant = true
                        cell.accessoryType = .disclosureIndicator
                        cell.selectionStyle = .none
                        cell.caninput = false
                        projinfo.0.map({$0?["gsProjName"].string})
                        .bind(to: cell.inputField.rx.text)
                        .disposed(by: bag)
                        projinfo.0.accept(projinfo.0.value)
                    }
                    else if j == 1 {
                        cell.nameLabel.text = "综合计划名称:"
                        cell.isimportant = false
                        cell.accessoryType = .none
                        cell.selectionStyle = .none
                        cell.caninput = false
                        projinfo.0.map({$0?["compositeName"].string})
                            .bind(to: cell.inputField.rx.text)
                            .disposed(by: bag)
                    } else {
                        cell.nameLabel.text = "分摊金额(元):"
                        cell.isimportant = false
                        cell.accessoryType = .none
                        cell.selectionStyle = .none
                        cell.caninput = true
                        cell.isnumber = true
                        projinfo.1.bind(to: cell.inputField.rx.text).disposed(by: bag)
                        cell.inputField.rx.text.bind(to: projinfo.1).disposed(by: bag)
                    }
                }
            }
        }
        
        for i in 0 ..< 5 {
            let id = "ImportTableViewCell" + String(self.tickets.count + 2) + String(i)
            tableView.register(ImportTableViewCell.classForCoder(), forCellReuseIdentifier: id)
            if let cell = self.tableView.dequeueReusableCell(withIdentifier: id) as? ImportTableViewCell{
                self.importantcells.append(cell)
                if i == 0 {
                    cell.nameLabel.text = "报销含税总金额(元):"
                    cell.isimportant = true
                    cell.caninput = false
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    self.bxhstotal.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.placeholder = "请输入"
                    cell.isnumber = true
                    cell.inputField.keyboardType = .numbersAndPunctuation
                    self.bxhstotal.accept(self.bxhstotal.value)
                } else if i == 1 {
                    cell.nameLabel.text = "报销含税总金额大写:"
                    cell.isimportant = false
                    cell.caninput = false
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    cell.inputField.placeholder = "-"
                    self.bxhstotalbig.bind(to: cell.inputField.rx.text).disposed(by: bag)
                } else if i == 2 {
                    cell.nameLabel.text = "报销不含税总金额(元):"
                    cell.isnumber = true
                    cell.isimportant = true
                    cell.caninput = false
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    self.bxnothstotal.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.placeholder = "请输入"
                    cell.inputField.keyboardType = .numbersAndPunctuation
                    self.bxnothstotal.accept(self.bxnothstotal.value)
                } else if i == 3 {
                    cell.nameLabel.text = "税额:"
                    cell.isimportant = false
                    cell.caninput = false
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    cell.inputField.placeholder = "-"
                    self.shuie.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.rx.text.bind(to: self.shuie).disposed(by: bag)
                } else if i == 4 {
                    cell.nameLabel.text = "报销事由:"
                    cell.isimportant = true
                    cell.caninput = true
                    cell.isnumber = false
                    cell.accessoryType = .none
                    cell.selectionStyle = .none
                    cell.inputField.rx.text.bind(to: self.reason).disposed(by: bag)
                    self.reason.bind(to: cell.inputField.rx.text).disposed(by: bag)
                    cell.inputField.placeholder = "请输入"
                }
            }
        }
    }
    
    var bigtypes: [JSON] = []
    
    var subtypes: [JSON] = []
    
    func getTypeList(id: String?){
        self.beginLoading()
        NetManager.get(AllBXType, ["pid": (id ?? "")], suc: { (json) in
            self.endLoading()
            if id == nil {
                self.bigtypes = json["data"].array ?? []
            } else {
                self.subtypes = json["data"].array ?? []
            }
        }) { (error) in
            self.endLoading()
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3 + tickets.count + self.projectSources.count
    }
    
    @objc func deltefile(button: UIButton){
        let tag = button.tag
        let index = tag - 10000
        self.files.remove(at: index)
        self.tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                //弹出选择框
                self.popalert(source: self.bigtypes, father: true)
            } else if indexPath.row == 1 {
                self.popalert(source: self.subtypes, father: false)
            }
        } else if indexPath.section <= self.tickets.count {
            self.currentticket = indexPath.section - 1
            if indexPath.row == 0 {
                self.poptickettype(source: self.tickettypes)
            } else if indexPath.row == 1 {
                self.poprats(source: self.rats)
            }
        } else if indexPath.section <= self.tickets.count + self.projectSources.count {
            if indexPath.row == 0 {
                self.selectedProj = indexPath.section - self.tickets.count - 1
                let vc = SearchProjectsViewController()
                vc.path = AllBXProjectList
                vc.selectedModels = self.projectSources.map({$0.0.value ?? JSON()})
                vc.title = "项目选择"
                vc.delegate = self
                self.push(destination: vc)
            }
        }
    }
    
    var selectedProj = 0//选中的项目
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if section < self.tickets.count {
            return 0
        }
        
        if section == self.tickets.count {
            return 40
        }
        
        if section == self.tickets.count + self.projectSources.count {
            return 40
        }
        
        if section == self.tickets.count + self.projectSources.count + 2 {
            return 40
        }
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if (section < self.tickets.count ) {return nil}
        if ( section == self.tickets.count ) {
            let view = UIView()
            let line = UIView()
            line.backgroundColor = tableView.separatorColor
            line.frame = CGRect(origin: CGPoint.init(x: 15, y: 0), size: CGSize(width: UIScreen.main.bounds.size.width - 15, height: 0.5))
            view.addSubview(line)
            view.backgroundColor = UIColor.white
            let button = UIButton.init(type: .system)
            button.backgroundColor = UIColor.white
            button.setTitle("+增加发票明细", for: .normal)
            button.setTitleColor(UIColor.mainColor, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            button.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 200, height: 39.5))
            button.left = UIScreen.main.bounds.size.width / 2 - 100
            button.top = 0.5;
            view.addSubview(button)
            button.addTarget(self, action: #selector(adddetail), for: .touchUpInside)
            return view
        } else if (section == self.tickets.count + self.projectSources.count) {
            let view = UIView()
            let line = UIView()
            line.backgroundColor = tableView.separatorColor
            line.frame = CGRect(origin: CGPoint.init(x: 15, y: 0), size: CGSize(width: UIScreen.main.bounds.size.width - 15, height: 0.5))
            view.addSubview(line)
            view.backgroundColor = UIColor.white
            let button = UIButton.init(type: .system)
            button.backgroundColor = UIColor.white
            button.setTitle("+新增项目", for: .normal)
            button.setTitleColor(UIColor.mainColor, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            view.addSubview(button)
            let remaining = UILabel()
            remaining.font = UIFont.systemFont(ofSize: 14)
            view.addSubview(remaining)
            self.remainingft.map({"剩余分摊金额" + String.init(format: "%.2f", $0 ?? 0.0) + "元"})
            .bind(to: remaining.rx.text).disposed(by: bag)
            self.remainingft.map({($0 ?? 0.0) >= 0})
                .subscribe { (event) in
                    if event.element == true {
                        remaining.textColor = .black
                    } else {
                        remaining.textColor = .red
                    }
            }.disposed(by: bag)
            button.snp.makeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.width.equalTo(80)
                make.height.equalTo(39.5)
                make.centerX.equalToSuperview()
            }
            remaining.numberOfLines = 0
            remaining.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.centerY.equalTo(button.snp.centerY)
                make.right.equalTo(button.snp.left)
            }
            remaining.adjustsFontSizeToFitWidth = true
            
            button.addTarget(self, action: #selector(addproj), for: .touchUpInside)
            return view
        } else if (section == self.tickets.count + self.projectSources.count + 2) {
            let view = UIStackView()
            view.alignment = .center
            view.axis = .horizontal
            view.distribution = .fillEqually
            let button = UIButton.init(type: .custom)
            button.setTitle("新增附件", for: .normal)
            button.setTitleColor(UIColor.mainColor, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            button.size = CGSize(width: 100, height: 30)
            button.addTarget(self, action: #selector(popaddfile), for: .touchUpInside)
            view.addArrangedSubview(button)
            return view
        }
        
        return nil
    }
    
    @objc func addproj(){
        self.projectSources.append((BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<String?>.init(value: nil)))
        self.sureForUse()
        self.tableView.beginUpdates()
        self.tableView.insertSections(IndexSet.init(integer: self.tickets.count + self.projectSources.count), with: .automatic)
        self.tableView.endUpdates()
        self.sureForUse()
        self.tableView.reloadSections(IndexSet.init(integer: self.tickets.count + 1), with: .automatic)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 4
        } else if section <= self.tickets.count {
            return 4
        } else if section <= self.tickets.count + self.projectSources.count {
            return 3
        } else if section == self.tickets.count + self.projectSources.count + 1 {
            return 5
        } else {
            return files.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {return 0}
        if section <= self.tickets.count + self.projectSources.count {
            return 40
        }
        if section == self.tickets.count + self.projectSources.count + 1 {
            return 0
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        if section == 0 {
            return nil
        } else if section < self.tickets.count + 1 {
            let view = UIView()
            view.backgroundColor = UIColor.hex("eeeeee")
            let label = UILabel.init()
            label.text = "发票明细" + "(" + String(section) + ")"
            label.textColor = UIColor.hex("666666")
            label.font = UIFont.systemFont(ofSize: 14)
            label.width = label.text!.size(with: label.font).width
            label.height = label.text!.size(with: label.font).height
            label.left = 15
            label.top = 22 - label.height / 2
            view.addSubview(label)
            if self.tickets.count != 1 && section > 1 {
                let button = UIButton.init(type: .system)
                button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
                button.setTitleColor(UIColor.mainColor, for: .normal)
                button.setTitle("删除", for: .normal)
                button.frame = CGRect.init(origin: CGPoint(x: self.view.width - 65, y: 5), size: CGSize.init(width: 50, height: 30))
                view.addSubview(button)
                button.tag = section - 1;
                button.addTarget(self, action: #selector(dlt(button:)), for: .touchUpInside)
            }
            return view
        } else if section <= self.tickets.count + self.projectSources.count {
            let view = UIView()
            view.backgroundColor = UIColor.hex("eeeeee")
            let label = UILabel.init()
            let idx = section - self.tickets.count
            label.text = "项目明细" + "(" + String(idx) + ")"
            label.textColor = UIColor.hex("666666")
            label.font = UIFont.systemFont(ofSize: 14)
            label.width = label.text!.size(with: label.font).width
            label.height = label.text!.size(with: label.font).height
            label.left = 15
            label.top = 22 - label.height / 2
            view.addSubview(label)
            let button = UIButton.init(type: .system)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            button.setTitleColor(UIColor.mainColor, for: .normal)
            button.setTitle("删除", for: .normal)
            button.frame = CGRect.init(origin: CGPoint(x: self.view.width - 65, y: 5), size: CGSize.init(width: 50, height: 30))
            if self.projectSources.count != 1 {
                view.addSubview(button)
                button.tag = idx - 1;
                button.addTarget(self, action: #selector(dltProj(button:)), for: .touchUpInside)
            }
            return view
        }
        else if section == self.tickets.count + self.projectSources.count + 2 {
            let footer = UIView()

            footer.backgroundColor = UIColor.dftBack

            footer.backgroundColor = UIColor.white

            let titleLbl = UILabel()

            titleLbl.textColor = UIColor.textColor

            titleLbl.font = UIFont.boldSystemFont(ofSize: 18)

            if self.files.count > 0 {
                titleLbl.text = "附件:"
            } else {
                titleLbl.text = "附件:无"
            }

            titleLbl.frame = CGRect(origin: CGPoint(x: 30, y: 0), size: CGSize(width: titleLbl.contentSize.width, height: titleLbl.contentSize.height))

            titleLbl.top = 20 - titleLbl.contentSize.height / 2

            footer.addSubview(titleLbl)

            let line = UIView()
            line.backgroundColor = tableView.separatorColor
            footer.addSubview(line)
            line.snp.makeConstraints { (make) in
                make.left.equalTo(15)
                make.right.equalToSuperview()
                make.top.equalToSuperview()
                make.height.equalTo(1)
            }
            return footer
        }
        return nil
    }
    
    @objc func dltProj(button: UIButton){
        let tag = button.tag
        self.projectSources.remove(at: tag)
        self.tableView.beginUpdates()
        let set = IndexSet.init(integersIn: self.tickets.count + 1 + tag ..< self.tickets.count + 2 + tag)
        self.tableView.deleteSections(set, with: .automatic)
        self.tableView.endUpdates()
        self.sureForUse()
        self.tableView.reloadData()
    }
}

extension RequestBaoXiaoViewController{
    
    @objc func dlt(button: UIButton){
        let tag = button.tag
        self.tickets.remove(at: tag)
        self.tableView.beginUpdates()
        let set = IndexSet.init(integersIn: 1 + tag ..< 2 + tag)
        self.tableView.deleteSections(set, with: .automatic)
        self.tableView.endUpdates()
        self.sureForUse()
        self.tableView.reloadData()
    }
    
    @objc func adddetail(){
        let value = (BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<JSON?>.init(value: nil),BehaviorRelay<String?>.init(value: nil),BehaviorRelay<String?>.init(value: nil))
        self.tickets.append(value)
        self.sureForUse()
        self.tableView.beginUpdates()
        self.tableView.insertSections(IndexSet.init(integer: self.tickets.count), with: .automatic)
        self.tableView.endUpdates()
        self.sureForUse()
        let all = self.tickets.reduce(0.0) { (result, element) -> Double in
            let total = Double.init(element.2.value ?? "") ?? 0.0//element.2
            return result + total
        }
        self.bxhstotal.accept(String.init(format: "%.2f", all))
        self.tableView.reloadSections(IndexSet.init(integer: self.tickets.count + 1), with: .automatic)
    }
    
    func popalert(source: [JSON],father: Bool){
        let alert = UIAlertController.init(title: "请选择报销类型", message: nil, preferredStyle: .actionSheet)
        for item in source {
            let action = UIAlertAction.init(title: item["name"].string, style: .default) { (alert) in
                if father {
                    self.getTypeList(id: item["id"].string)
                    self.bigtype.onNext(item)
                    self.subtype.onNext(nil)
                } else {
                    self.subtype.onNext(item)
                }
            }
            alert.addAction(action)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func popaddfile()->Void{
        
        let alert = UIAlertController.init(title: "选取附件", message: nil, preferredStyle: .actionSheet)
        
        let photo = UIAlertAction.init(title: "照片", style: .default) { (action) in
            
            if 9 - self.files.count > 0 {
                if let picker = TZImagePickerController.init(maxImagesCount: 9 - self.files.count, delegate: self) {
                    
                    func pick(images: Array<UIImage>?, assets: Array<Any>?,isselectorigin: Bool) -> Void {
                        guard images != nil else {
                            self.alert("获取图片失败")
                            return
                        }
                        guard assets != nil else {
                            self.alert("获取图片失败")
                            return
                        }
                        for i in 0 ..< images!.count {
                            let image = images![i]
                            let asset = assets![i] as! PHAsset
                            if asset.value(forKey: "filename") != nil {
                                self.files.append((image,asset.value(forKey: "filename")! as! String))
                            } else {
                                self.files.append((image,String(i) + ".png"))
                            }
                        }
                        let set = IndexSet.init(integer: self.tickets.count + 2)
                        let id = "ImportTableViewCell" + String(self.tickets.count + 2) + String(self.files.count - 1)
                        self.tableView.register(ImportTableViewCell.classForCoder(), forCellReuseIdentifier: id)
                        self.tableView.beginUpdates()
                        self.tableView.reloadSections(set, with: .automatic)
                        self.tableView.endUpdates()
                    }
                    
                    picker.didFinishPickingPhotosHandle = pick
                    
                    self.present(picker, animated: true, completion: nil)
                }
            } else {
                self.alert("附件多做选9张")
            }
            
        }
        
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
            
        }
        alert.addAction(photo)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    func poptickettype(source: [JSON]){
        let alert = UIAlertController.init(title: "请选择发票类型", message: nil, preferredStyle: .actionSheet)
        for item in source {
            let action = UIAlertAction.init(title: item["invoicesType"].string, style: .default) { (alert) in
                self.tickets[self.currentticket].0.accept(item)
                self.tableView.reloadData()
            }
            alert.addAction(action)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    func poprats(source: [JSON]){
        let alert = UIAlertController.init(title: "请选择税率", message: nil, preferredStyle: .actionSheet)
        for item in source {
            let action = UIAlertAction.init(title: item["taxrateType"].string, style: .default) { (alert) in
                self.tickets[self.currentticket].1.accept(item)
                self.tableView.reloadData()
            }
            alert.addAction(action)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
}




extension RequestBaoXiaoViewController{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let section = indexPath.section
        let row = indexPath.row
        if section == 0 {
            if row < self.importantcells.count {
                return self.importantcells[row]
            } else {
                return UITableViewCell()
            }
        } else if section > 0 && section <= self.tickets.count {
            if 4 + (section - 1) * 4  + row < self.importantcells.count {
                let cell =  self.importantcells[4 + (section - 1) * 4 + row]
                return cell
            } else {
                return UITableViewCell()
            }
        } else if section > self.tickets.count && section <= self.tickets.count + self.projectSources.count {
            let secidx = section - self.tickets.count - 1
            let idx = 4 * (self.tickets.count + 1) + 3 * secidx + row
            if idx < self.importantcells.count {
                let cell = self.importantcells[idx]
                return cell
            } else {
                return UITableViewCell()
            }
        } else if section == self.tickets.count + self.projectSources.count + 1 {
            let idx = 4 + 4 * self.tickets.count + 3 * self.projectSources.count + row
            if idx < self.importantcells.count {
                return self.importantcells[idx]
            } else {
                return UITableViewCell()
            }
        } else {
            var cell = tableView.dequeueReusableCell(withIdentifier: "FileCell")
            if cell == nil {
                cell = UITableViewCell.init(style: .default, reuseIdentifier: "FileCell")
                cell?.accessoryType = .none
                let delbtn = UIButton.init(type: .custom)
                delbtn.addTarget(self, action: #selector(deltefile(button:)), for: .touchUpInside)
                delbtn.setImage(UIImage(named: "icon_cancel"), for: .normal)
                delbtn.tag = 10000 + indexPath.row
                cell?.contentView.addSubview(delbtn)
                delbtn.frame = CGRect.init(origin: CGPoint.init(x: tableView.width - 30, y: 22.5), size: CGSize(width: 15, height: 15))
                cell?.textLabel?.text = files[indexPath.row].1
                cell?.imageView?.image = UIImage.init(named: "image")
                cell?.imageView?.contentMode = .scaleAspectFill
                cell?.imageView?.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 30, height: 30))
                cell?.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
                cell?.textLabel?.textColor = UIColor.hex("333333")
                cell?.selectionStyle = .none
            }
            return cell!
        }
        
//        if section == self.tickets.count + self.projectSources.count + 1 {
//            let idx = 4 * self.tickets.count + 3 * self.projectSources.count
//            return self.importantcells[idx]
//        }
        
//        if section == self.tickets.count + self.projectSources.count + 2 {
//            var cell = tableView.dequeueReusableCell(withIdentifier: "FileCell")
//            if cell == nil {
//                cell = UITableViewCell.init(style: .default, reuseIdentifier: "FileCell")
//                cell?.accessoryType = .none
//                let delbtn = UIButton.init(type: .custom)
//                delbtn.addTarget(self, action: #selector(deltefile(button:)), for: .touchUpInside)
//                delbtn.setImage(UIImage(named: "icon_cancel"), for: .normal)
//                delbtn.tag = 10000 + indexPath.row
//                cell?.contentView.addSubview(delbtn)
//                delbtn.frame = CGRect.init(origin: CGPoint.init(x: tableView.width - 30, y: 22.5), size: CGSize(width: 15, height: 15))
//                cell?.textLabel?.text = files[indexPath.row].1
//                cell?.imageView?.image = UIImage.init(named: "image")
//                cell?.imageView?.contentMode = .scaleAspectFill
//                cell?.imageView?.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 30, height: 30))
//                cell?.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
//                cell?.textLabel?.textColor = UIColor.hex("333333")
//                cell?.selectionStyle = .none
//            }
//            return cell!
//        }
    }
    
    func index(for section: Int)->Int{
        if section < 0 {
            return 0
        }
        if self.tickets.count > section {
            return section
        } else {
            return self.index(for: section - 1)
        }
    }
    
    
//    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//        let section = indexPath.section
//        let row = indexPath.row
//        if section == 0 || section == self.tickets.count + 1 {
//            let id = "ImportTableViewCell" + String(indexPath.section) + String(indexPath.row)
//            if let cell = tableView.dequeueReusableCell(withIdentifier: id) as? ImportTableViewCell {
//                if section == 0 {
//                    if row == 0 {
//                        self.projectinfo
//                            .subscribe(onNext: { (str) in
//                                cell.inputField.text = str?["gsProjName"].string
//                            })
//                            .disposed(by: bag)
//                    } else if row == 1 {
//                        self.comprehensivePlan
//                            .subscribe(onNext: { (str) in
//                                cell.inputField.text = str
//                            })
//                            .disposed(by: bag)
//                    } else if row == 2 {
//                        self.bigtype.subscribe(onNext: { (str) in
//                            cell.inputField.text = str?["name"].string
//                        }).disposed(by: bag)
//                    } else if row == 3 {
//                        self.subtype.subscribe(onNext: { (str) in
//                            cell.inputField.text = str?["name"].string
//                        }).disposed(by: bag)
//                    } else if row == 5 {
//                        phone.bind(to: cell.inputField.rx.text).disposed(by: bag)
//                        cell.inputField.rx.text.bind(to: self.phone).disposed(by: bag)
//                        cell.inputField.placeholder = "请输入"
//                        cell.inputField.keyboardType = .phonePad
//                    }
//                } else if indexPath.section == self.tickets.count + 1 {
//                    if indexPath.row == 0 {
//                        cell.inputField.rx.text.bind(to: self.bxhstotal).disposed(by: bag)
//                        self.bxhstotal.bind(to: cell.inputField.rx.text).disposed(by: bag)
//                        let total = self.tickets.reduce(0.0) { (result, element) -> Double in
//                            let totalstr = element.2
//                            let totalval = Double.init(totalstr ?? "") ?? 0.0
//                            return result + totalval
//                        }
//                        self.bxhstotal.accept(String.init(format: "%.2f", total))
//                    } else if indexPath.row == 1 {
//                        self.bxhstotalbig.bind(to: cell.inputField.rx.text).disposed(by: bag)
//                        let total = self.tickets.reduce(0.0) { (result, element) -> Double in
//                            let totalstr = element.2
//                            let totalval = Double.init(totalstr ?? "") ?? 0.0
//                            return result + totalval
//                        }
//                        self.bxhstotal.accept(String.init(format: "%.2f", total))
//                        self.bxhstotalbig.accept(String.init(format: "%.2f", total).rmbOldStyle)
//                    } else if indexPath.row == 2 {
//                        cell.inputField.rx.text.bind(to: self.bxnothstotal).disposed(by: bag)
//                        self.bxnothstotal.bind(to: cell.inputField.rx.text).disposed(by: bag)
//                        let partial = self.tickets.reduce(0.0) { (result, element) -> Double in
//                            let partialstr = element.3
//                            let partialaccount = Double.init(partialstr ?? "") ?? 0.0
//                            return result + partialaccount
//                        }
//                        self.bxnothstotal.accept(String.init(format: "%.2f", partial))
//                    } else if indexPath.row == 3 {
//                        self.shuie.bind(to: cell.inputField.rx.text).disposed(by: bag)
//                        cell.inputField.rx.text.bind(to: self.shuie).disposed(by: bag)
//                        let total = self.tickets.reduce(0.0) { (result, element) -> Double in
//                            let totalstr = element.2
//                            let totalval = Double.init(totalstr ?? "") ?? 0.0
//                            return result + totalval
//                        }
//                        let partial = self.tickets.reduce(0.0) { (result, element) -> Double in
//                            let partialstr = element.3
//                            let partialaccount = Double.init(partialstr ?? "") ?? 0.0
//                            return result + partialaccount
//                        }
//                        self.shuie.accept(String.init(format: "%.2f", total - partial))
//                    }
//                }
//            }
//        }
//    }
}
